/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package interfaz.plantillas;

import entidades.Contacto;
import entidades.DatosPersonales;
import entidades.Enumeraciones;
import entidades.Identificacion;
import exceptions.ValoresIncompletosException;
import exceptions.ValoresIncorrectosException;
import interfaces.PlantillaRegistro;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Calendar;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import utiles.JFileChooserHelper;
import utiles.UtilesCalendar;
import utiles.UtilesImage;

/**
 *
 * @author fcarou
 */
public class PlantillaDatosPersonales extends javax.swing.JPanel implements PlantillaRegistro
{
    private DatosPersonales datos;
    
    private PlantillaIdentificacion plantillaIdentificacion;
    private PlantillaContacto plantillaContacto;

    /**
     * Creates new form PlantillaDatosPersonales
     * @param datos
     */
    public PlantillaDatosPersonales(DatosPersonales datos)
    {
        this.datos = datos;
        
        initComponents();
        
        plantillaIdentificacion = new PlantillaIdentificacion(datos.getIdentificacion());
        plantillaContacto = new PlantillaContacto(datos.getContacto());
        
        setUpPanel(panelIdentificacion, plantillaIdentificacion);
        setUpPanel(panelContacto, plantillaContacto);
        
        setCampoNacimiento();
        setImagenLabel();
    }
    
    private void setCampoNacimiento ()
    {
        Calendar nacimiento = datos.getFechaNacimiento();
        
        if (nacimiento != null)
            campoNacimiento.setText(UtilesCalendar.getString(nacimiento));
    }
    
    private void setImagenLabel ()
    {
        if (datos.getImagen() == null)
            return;
        
        BufferedImage imagen = UtilesImage.ByteArrayAImage(datos.getImagen());
        BufferedImage res = UtilesImage.resize(imagen, 150, 150);
        labelImagen.setIcon(new ImageIcon(res));
    }
    
    private void setUpPanel (JPanel panel, JPanel agregar)
    {
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(agregar);
    }

    public DatosPersonales getDatos()
    {
        return datos;
    }

    public void setDatos(DatosPersonales datos)
    {
        this.datos = datos;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        panelIdentificacion = new javax.swing.JPanel();
        panelContacto = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        campoNacimiento = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        comboEstado = new javax.swing.JComboBox();
        labelImagen = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        botonSeleccionarImagen = new javax.swing.JButton();
        botonTutor = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos Personales", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.gray));

        javax.swing.GroupLayout panelIdentificacionLayout = new javax.swing.GroupLayout(panelIdentificacion);
        panelIdentificacion.setLayout(panelIdentificacionLayout);
        panelIdentificacionLayout.setHorizontalGroup(
            panelIdentificacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        panelIdentificacionLayout.setVerticalGroup(
            panelIdentificacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 175, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout panelContactoLayout = new javax.swing.GroupLayout(panelContacto);
        panelContacto.setLayout(panelContactoLayout);
        panelContactoLayout.setHorizontalGroup(
            panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        panelContactoLayout.setVerticalGroup(
            panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 278, Short.MAX_VALUE)
        );

        jLabel1.setText("Fecha nacimiendo [DD/MM/AAAA]");

        campoNacimiento.addFocusListener(new java.awt.event.FocusAdapter()
        {
            public void focusLost(java.awt.event.FocusEvent evt)
            {
                campoNacimientoFocusLost(evt);
            }
        });

        jLabel2.setText("Estado civil");

        comboEstado.setModel(new DefaultComboBoxModel(Enumeraciones.EstadoCivil.values()));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${datos.estadoCivil}"), comboEstado, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        jLabel3.setText("Imagen:");

        botonSeleccionarImagen.setText("Seleccionar");
        botonSeleccionarImagen.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                botonSeleccionarImagenActionPerformed(evt);
            }
        });

        botonTutor.setText("Tutor");
        botonTutor.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                botonTutorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(comboEstado, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(panelContacto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(panelIdentificacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(labelImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(botonSeleccionarImagen))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(campoNacimiento)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botonTutor)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(panelIdentificacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelImagen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelContacto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoNacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botonTutor))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comboEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(botonSeleccionarImagen))
                .addContainerGap(95, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void botonSeleccionarImagenActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_botonSeleccionarImagenActionPerformed
    {//GEN-HEADEREND:event_botonSeleccionarImagenActionPerformed
        File imagen = JFileChooserHelper.tomarArchivo(this);
        
        if (imagen == null)
            return;
        
        String ext = this.getExtension(imagen.getName());
        
        if (ext == null || ext.equals(""))
        {
            JOptionPane.showMessageDialog(this, "Error al obtener la extensión del archivo.");
            return;
        }
        
        try
        {
            BufferedImage buff = ImageIO.read(imagen);
            BufferedImage buff2 = UtilesImage.toBufferedImage(buff.getScaledInstance(300, 300, Image.SCALE_SMOOTH));
            byte[] imagenBytes = UtilesImage.imagenAByteArray(buff2, ext);
            
            datos.setImagen(imagenBytes);
            setImagenLabel();
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(this, "Falló la conversión de la imagen.\nAsegúrese que esté en un formato como JPG.");
            e.printStackTrace();
        }
    }//GEN-LAST:event_botonSeleccionarImagenActionPerformed

    private void botonTutorActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_botonTutorActionPerformed
    {//GEN-HEADEREND:event_botonTutorActionPerformed
        
    }//GEN-LAST:event_botonTutorActionPerformed

    private void campoNacimientoFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_campoNacimientoFocusLost
    {//GEN-HEADEREND:event_campoNacimientoFocusLost
        Calendar c = UtilesCalendar.construirCalendar(campoNacimiento.getText());
        
        if (c != null)
            datos.setFechaNacimiento(c);
    }//GEN-LAST:event_campoNacimientoFocusLost
    
    private String getExtension (String file)
    {
        String extension = "";

        int i = file.lastIndexOf('.');
        
        if (i > 0)
            extension = file.substring(i+1);
        
        return extension;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonSeleccionarImagen;
    private javax.swing.JButton botonTutor;
    private javax.swing.JTextField campoNacimiento;
    private javax.swing.JComboBox comboEstado;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel labelImagen;
    private javax.swing.JPanel panelContacto;
    private javax.swing.JPanel panelIdentificacion;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    @Override
    public Object getDato() throws ValoresIncorrectosException, ValoresIncompletosException
    {
        datos.setContacto((Contacto) plantillaContacto.getDato());
        datos.setIdentificacion((Identificacion) plantillaIdentificacion.getDato());
        
        if (datos.getFechaNacimiento() == null)
            throw new ValoresIncompletosException("No ha completado la fecha de nacimiento.");
        
        if (datos.getImagen() == null)
            throw new ValoresIncompletosException("Debe seleccionar una imagen.");
        
        return datos;
    }
}
